import { getUserInfo, sceneRecord } from '../../api/user'
import { apiAddress } from '../../utils/config'
import { approvalStatusOptions } from '../../utils/options'
import { isLogin } from '../../utils/permission'
import { debounce } from '../../utils/util'

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    approvalStatusOptions,
    list: [],
    currentPage: 1,
    type: 'loading',
    loading: false,
    baseUrl: apiAddress,
    isLogin: false,
    userInfo: {},
    pageLoading: true,
    canLoadList: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._init()
    // 监听事件
    app.event.on('userInfoChanged', this._userInfoChanged)
    app.event.on('listChanged', this._onListChanged)
    app.event.on('loginStatusChanged', this._onLoginStatusChanged)
  },

  onUnload: function () {
    app.event.removeListener('userInfoChanged', this._userInfoChanged)
    app.event.removeListener('listChanged', this._onListChanged)
    app.event.removeListener('loginStatusChanged', this._onLoginStatusChanged)
  },

  onReachBottom() {
    if (this.data.type == 'end' || this.data.loading) return
    this.setData({ currentPage: this.data.currentPage + 1 })
    this._getData()
  },

  onPullDownRefresh: function () {
    this._setLoginStatus()
    if (!this.data.isLogin || !this.data.userInfo.name) return wx.stopPullDownRefresh()
    this._onRefresh()
  },

  _init: debounce(function () {
    this.setData({
      currentPage: 1,
      list: [],
      pageLoading: true
    })
    this._setUserInfo()
    this._setLoginStatus()
    if (!this.data.isLogin) return this.setData({ pageLoading: false })
    if (!this.data.userInfo.name) {
      this._getUserInfo()
        .then(() => {
          return this.data.userInfo.name && this._getData()
        })
        .finally(() => {
          this.setData({ pageLoading: false })
        })
    } else {
      this._getData().finally(() => {
        this.setData({ pageLoading: false })
      })
    }
  }, 300),

  _onListChanged: function () {
    this.setData({
      currentPage: 1,
      list: []
    })
    this._getData()
  },

  _onLoginStatusChanged: function () {
    this._init()
  },

  _userInfoChanged: function () {
    !this.data.canLoadList && this._init()
  },

  _getUserInfo: function () {
    return getUserInfo().then((res) => {
      if (res.code == 200) {
        this.setData({
          userInfo: res.data
        })
      }
    })
  },

  _setUserInfo: function () {
    this.setData({
      userInfo: app.globalData.userInfo
    })
  },

  _setLoginStatus: function () {
    this.setData({
      isLogin: isLogin()
    })
  },

  _onRefresh: function () {
    if (this._freshing) return
    this._freshing = true
    this.setData({
      type: 'loading',
      currentPage: 1,
      list: []
    })
    this._getData()
      .then(() => {
        wx.showToast({
          title: '刷新成功',
          icon: 'success'
        })
      })
      .finally(() => {
        wx.stopPullDownRefresh()
        this._freshing = false
      })
  },

  _getData: function () {
    this.setData({
      loading: true,
      canLoadList: true
    })
    return sceneRecord({
      page: this.data.currentPage
    })
      .then((res) => {
        if (res.code === 200) {
          this.setData({
            list: [...this.data.list, ...res.data.data]
          })
          if (this.data.currentPage >= res.data.last_page) {
            this.setData({
              type: 'end'
            })
          }
        }
      })
      .finally(() => {
        this.setData({
          loading: false
        })
      })
  },

  _takePhoto: function () {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image']
    })
      .then((res) => {
        let tempFilePath = res.tempFiles[0].tempFilePath
        wx.navigateTo({
          url: '/pages/submit/submit?tempFilePath=' + tempFilePath
        })
      })
      .catch(() => {})
  },

  _add: function () {
    if (!this.data.isLogin)
      return wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    wx.navigateTo({
      url: '/pages/submit/submit'
    })
  },

  _toDetail: function () {
    wx.navigateTo({
      url: '/pages/list/detail/detail'
    })
  },

  _scrollToLLower: function (e) {
    console.log(123)
    let direction = e.detail.direction
    if (direction != 'bottom' || this.data.type == 'end' || this.data.loading)
      return
    this.setData({ currentPage: this.data.currentPage + 1 })
    this._getData()
  }
})
